<template>
  <div class="page-table">
    <div class="page-filter">
      <div class="query">
        <el-form size="mini">
          <el-row :gutter="4">
            <el-col :span="3">
              <el-form-item>
                <el-input v-model="searchQuery.name" placeholder="公司名称" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item>
                <el-input v-model="searchQuery.linkmanName" placeholder="联系人" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item>
                <el-input v-model="searchQuery.linkmanPhone" placeholder="联系电话" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item>
                <el-input v-model="searchQuery.driverName" placeholder="司机姓名" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item>
                <el-input v-model="searchQuery.driverPhone" placeholder="司机电话" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-button size="mini" type="primary" plain @click="companyGetInitList()">查询</el-button>
              <el-button type="success" size="mini" @click="downExcelTemp('通讯录模板.xlsx')" v-permission="['admin','company:download']">下载模板</el-button>
              <el-button size="mini" type="primary" plain @click.native="batchImport" v-permission="['admin','company:import']">导入</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="op">
      </div>
    </div>
    <div class="grid">
      <div class="left">
        <div class="item">
          <div class="item-inner" ref="height">
            <div class="title-bar">
              <h2>企业通讯录</h2>
              <div class="op">
                <el-button size="mini" type="primary" plain @click="companyAdd" v-permission="['admin','company:add']">新增</el-button>
                <el-button size="mini" type="primary" plain :disabled="!companySelectedRow" @click="companyEdit()">修改</el-button>
                <el-button size="mini" type="primary" plain :disabled="!companySelectedRow" @click="companyDel">删除</el-button>
                <el-button size="mini" type="primary" plain :disabled="!companySelectedRow" @click="editDriver">查看司机</el-button>
                <el-button size="mini" type="primary" plain :disabled="!companySelectedRow" @click="setDefaultCompany">设为默认公司</el-button>
              </div>
            </div>
            <ad-table :data="companyList" :show-summary="companySummary" v-loading="companyInitLoading" u-table
                      :data-changes-scroll-top="companyIsScrollTop"
                      @row-click="companySelectRow" :searchQuery="companySearchQuery"
                      @search="companyGetInitList"
                      @sort-change="companySortInitList" @filter-change="companyFilterInitList"
                      @table-body-scroll="companyGetMoreList" :height="tableHeight">
              <ad-table-column label="序号" type="index" ctype="index" fixed/>
              <ad-table-column label="审核状态" prop="hasCheck" dictName="yes_or_no" filterable w="4c1f"/>
              <ad-table-column label="公司名称" prop="name" w="4c1f"/>
              <!-- href="/relationd/company" -->
              <ad-table-column label="默认公司" prop="hasSelf" w="4c1f">
                <template v-slot="scope">
                  <span v-if="scope.row.hasSelf == 1">是</span>
                  <span  v-else>否</span>
                </template>
              </ad-table-column>
              <ad-table-column label="类型" prop="type" dictName="customer_type" filterable w="2c1f"/>
              <ad-table-column label="是否月结" prop="nature" dictName="yes_or_no" filterable w="4c1f"/>
              <ad-table-column label="承运台数" prop="transportCount" w="4c"/>
              <ad-table-column label="应付总额" prop="paymentFee" sortable w="4c1f"/>
              <ad-table-column label="已付" prop="hasPaymentFee" sortable w="2c1f"/>
              <ad-table-column label="未付" prop="unPaymentFee" sortable w="2c1f"/>
              <ad-table-column label="下单台数" prop="orderCount" w="4c"/>
              <ad-table-column label="应收总额" prop="collectionFee" sortable w="4c1f"/>
              <ad-table-column label="已收" prop="hasCollectionFee" sortable w="2c1f"/>
              <ad-table-column label="未收" prop="unCollectionFee" sortable w="2c1f"/>
              <ad-table-column label="近一次接单时间" ctype="datetime" prop="lastTransportTime" sortable width="140"/>
              <ad-table-column label="近一次下单时间" ctype="datetime" prop="lastOrderTime" sortable width="140"/>
            </ad-table>
          </div>
        </div>
      </div>
      <div class="right">
        <div class="item">
          <div class="title-bar">
            <h2>联系人列表</h2>
            <div class="op">
              <el-button size="mini" type="primary" plain :disabled="!companySelectedRow" @click="linkmanAdd" v-permission="['admin','linkman:add']">新增</el-button>
              <el-button size="mini" type="primary" plain :disabled="!linkmanSelectedRow" @click="linkmanEdit()">修改</el-button>
              <el-button size="mini" type="primary" plain :disabled="!linkmanSelectedRow" @click="linkmanDel">删除</el-button>
              <el-button size="mini" type="primary" plain :disabled="!linkmanSelectedRow || !!linkmanSelectedRow.hasCheck" @click="openLinkmanCheckAdder" v-permission="['admin','linkman:check']">审核</el-button>
<!--              <el-button size="mini" type="primary" plain :disabled="!linkmanSelectedRow" @click="changeSeller">更改业务员</el-button>-->
            </div>
          </div>
          <ad-table :data="linkmanList" v-loading="linkmanInitLoading" u-table
                    @row-click="linkmanSelectRow" :height="206">
            <ad-table-column label="序号" type="index" ctype="index" fixed/>
            <ad-table-column label="审核状态" prop="hasCheck" dictName="yes_or_no" w="4c1f"/>
            <ad-table-column label="联系人" prop="name"/>
            <ad-table-column label="联系电话" prop="phone"/>
            <ad-table-column label="城市" prop="city" ctype="city"/>
            <ad-table-column label="接单数量" prop="transportCount"/>
            <ad-table-column label="应付总额" prop="paymentFee"/>
            <ad-table-column label="已付" prop="hasPaymentFee"/>
            <ad-table-column label="未付" prop="unPaymentFee"/>
            <ad-table-column label="下单数量" prop="orderCount"/>
            <ad-table-column label="应收总额" prop="collectionFee"/>
            <ad-table-column label="已收" prop="hasCollectionFee"/>
            <ad-table-column label="未收" prop="unCollectionFee"/>
            <ad-table-column label="近一次接单时间" prop="lastOrderTime" ctype="datetime"/>
            <ad-table-column label="近一次下单时间" prop="lastTransportTime" ctype="datetime"/>
            <ad-table-column label="添加人" prop="createUserName"/>
          </ad-table>
        </div>
        <div class="item">
          <div class="title-bar">
            <h2>订单列表</h2>
            <div class="op">
              <el-date-picker size="mini" v-model="orderSearchQuery.year" type="year" value-format="yyyy" placeholder="选择年"/>
              <el-button size="mini" type="primary" plain :disabled="!companySelectedRow" @click="orderGetInitList('6')">查询</el-button>
            </div>
          </div>
          <ad-table :data="orderList" v-loading="orderInitLoading" u-table
                    @table-body-scroll="orderGetMoreList" :height="bottomHeight">
            <ad-table-column label="序号" type="index" ctype="index" fixed/>
            <ad-table-column label="类型" prop="type" dictName="company_order_type"/>
<!--            <ad-table-column label="费用类型" prop="feeType"/>-->
            <ad-table-column label="金额" prop="fee"/>
            <ad-table-column label="订单编号" prop="orderSubNo"/>
            <ad-table-column label="联系人" prop="linkmanName"/>
            <ad-table-column label="联系电话" prop="linkmanPhone"/>
            <ad-table-column label="制单人" prop="orderCreateUserName"/>
            <ad-table-column label="制单时间" prop="orderCreateTime" ctype="datetime"/>
            <ad-table-column label="指派人" prop="assignUserName"/>
            <ad-table-column label="指派时间" prop="assignTime" ctype="datetime"/>
            <ad-table-column label="车辆名称" prop="carName"/>
            <ad-table-column label="车架/车牌号" prop="vin"/>
            <ad-table-column label="出发地" prop="startCode" ctype="city"/>
            <ad-table-column label="目的地" prop="destinationCode" ctype="city"/>
            <ad-table-column label="司机姓名" prop="driverName"/>
            <ad-table-column label="司机电话" prop="driverPhone"/>
          </ad-table>
        </div>
      </div>
    </div>
    <el-dialog title="公司" :visible.sync="companyAdder.visible" custom-class="ad-dialog" width="1000px">
      <company-adder :mode="companyAdder.mode" :id="companySelectedRowId" :visible.sync="companyAdder.visible" @saved="companySaved"/>
    </el-dialog>
    <el-dialog title="联系人" :visible.sync="linkmanAdder.visible" custom-class="ad-dialog" width="1000px">
      <linkman-adder :mode="linkmanAdder.mode" :id="linkmanSelectedRowId" :data="companySelectedRow" :visible.sync="linkmanAdder.visible" @saved="linkmanSaved"/>
    </el-dialog>
    <el-dialog title="司机管理" :visible.sync="driverAdder.visible" custom-class="ad-dialog" width="1000px">
      <driver-adder :mode="driverAdder.mode" :id="companySelectedRowId" :visible.sync="driverAdder.visible" @saved="companyGetInitList"/>
    </el-dialog>
    <el-dialog title="审核" :visible.sync="linkmanCheckAdder.visible" custom-class="ad-dialog" width="1220px">
      <linkman-verify-adder :mode="linkmanCheckAdder.mode" :id="linkmanSelectedRowId" :visible.sync="linkmanCheckAdder.visible" @saved="linkmanVerified"/>
    </el-dialog>
    <el-dialog title="更改业务员" :visible.sync="sellerSelector.visible" custom-class="ad-dialog" width="500px" top="180px">
      <seller :id="linkmanSelectedRowId" :visible.sync="sellerSelector.visible" @saved="orderSaved"/>
    </el-dialog>
    <!--批量导入模板-->
    <el-dialog :show-close="false" title="导入" width="500px" :visible.sync="batchImportVisible"
               :close-on-click-modal="false">
      <el-form ref="batchImportForm" :model="batchImportForm" label-width="130px" size="small">
        <div class="ad-block">
          <el-upload
              class="avatar-uploader"
              accept=".xlsx,.xls"
              ref="uploadFile"
              :headers="headers"
              :auto-upload="false"
              :action="url+'api/company/import-excel'"
              :on-success="onSuccess"
              :on-change="fileChange"
              :file-list="fileList"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
          >
            <el-button :disabled="isExcel" slot="trigger" size="small" type="primary">选择EXCEL</el-button>
            <el-input v-model="this.batchImportForm.fileName" size="small" style="width:230px;"
                      :readonly="true"></el-input>
            <el-button :disabled="isExcel" size="small" type="success" @click="uploadExcel">导入文件</el-button>
          </el-upload>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="batchImportVisible = false" size="small">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Value from '@/components/AdValue'
import AdTable from '@/components/AdTable'
import AdTableColumn from '@/components/AdTable/AdTableColumn'
import companyAdder from './dialog/companyAdder'
import linkmanAdder from './dialog/linkmanAdder'
import driverAdder from './dialog/driverAdder'
import linkmanVerifyAdder from './dialog/linkmanVerifyAdder'
import seller from './dialog/seller'
import adTable from '@/mixins/adTable'
import {getList as companyApiGetList, del as companyApiDel,companyHasSelf} from '@/api/relation/company'
import {getList as linkmanApiGetList, del as linkmanApiDel} from '@/api/relation/linkman'
import {getList as orderApiGetList} from '@/api/relation/order'
import {getToken} from '@/utils/auth'
import moment from 'moment'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'

export default {
  components: {Value, AdTable, AdTableColumn, companyAdder, linkmanAdder, driverAdder, linkmanVerifyAdder, seller},
  dicts: ['yes_or_no', 'customer_type','company_order_type'],
  mixins: [adTable([
    {name: 'company'},
    {name: 'linkman', parent: 'company'},
    {name: 'order', parent: 'company'}
  ])],
  data() {
    return {
      searchQuery: {},
      tableHeight: document.documentElement.clientHeight - 178,
      bottomHeight: document.documentElement.clientHeight - 424,
      driverAdder: {
        visible: false,
        mode: ''
      },
      linkmanCheckAdder: {
        visible: false,
        mode: ''
      },
      sellerSelector: {
        visible: false,
      },
      batchImportVisible: false,
      batchImportForm: {
        fileName: '',
        filePath: '',
        file: '',
        customizationData: {
          time: moment().locale('zh-cn').format('YYYYMMDDHHmmss')
        },
        saveList: []
      },
      headers: {
        'Authorization':'Bearer '+ Vue.ls.get(ACCESS_TOKEN),
      },
      fileList: [],
      url: localStorage.getItem('GATEWAY'),
      isExcel: false
    }
  },
  created() {
    this.companyGetInitList()
  },
  methods: {
    companyApiGetList, companyApiDel, linkmanApiGetList, linkmanApiDel, orderApiGetList,
    companyAfterSelectRow() {
      this.linkmanGetInitList()
      this.orderGetInitList()
    },
    // 下载模板
    downExcelTemp(fileUrl) {
      location.href = "../../static/template/" + fileUrl;
    },
    //批量导入
    batchImport() {
      this.batchImportVisible = true;
      this.batchImportForm.fileName = '';
      this.batchImportForm.file = '';
      this.batchImportForm.saveList = [];
    },
    uploadExcel() {
      this.isExcel = true;
      this.$refs.uploadFile.submit();
    },
    onSuccess() {
      this.isExcel = false;
      this.batchImportVisible = false;
      this.$notify({title: "导入", message: '导入成功', position: 'bottom-right', type: 'success'});
    },
    fileChange(file, fileList) {
      this.batchImportForm.file = file.raw;
      this.batchImportForm.fileName = file.name;
      if (file.status == 'ready') {
        const Xls = file.name.split('.');
        if (Xls[1] === 'xls' || Xls[1] === 'xlsx') {
          return file;
        } else {
          this.$notify({title: "上传文件", message: '文件格式不正确', position: 'bottom-right', type: 'warning'});
          this.batchImportForm.fileName = '';
          this.batchImportForm.file = '';
          return false
        }
      }
    },
    beforeAvatarUpload(file) {
      const Xls = file.name.split('.');
      if (Xls[1] === 'xls' || Xls[1] === 'xlsx') {
        return file;
      } else {
        this.$notify({title: "上传文件", message: '文件格式不正确', position: 'bottom-right', type: 'warning'});
        this.batchImportForm.fileName = '';
        return false
      }
    },
    setDefaultCompany() {
      this.$confirm('确认设置为默认公司吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        companyHasSelf({id:this.companySelectedRowId}).then(() => {
          this.$notify({title: "设置默认公司", message: '设置成功', position: 'bottom-right', type: 'success'});
          this.companyGetInitList()
        })
      }).catch(() => {
      });
    },
    editDriver() {
      this.openDriverAdder('edit')
    },
    openDriverAdder(mode) {
      this.driverAdder.visible = true
      if (mode == 'edit') {
        this.driverAdder.mode = mode
      } else {
        this.driverAdder.mode = ''
      }
    },
    openLinkmanCheckAdder() {
      this.linkmanCheckAdder.visible = true
      this.linkmanCheckAdder.mode = 'edit'
    },
    linkmanVerified(row) {
      this.companyGetInitList()
      this.linkmanList = []
      this.orderList = []
      // this.companySelectedRow.hasCheck = 1
      // this.linkmanGetInitList()
    },
    changeSeller() {
      this.sellerSelector.visible = true
    }
  }
}
</script>

<style lang="scss" scoped>
.page-table { display: flex; flex: 1; flex-direction: column;
  .grid {
    //display: grid;
    //flex: 1;
    border: 1px solid #e3e3e3;
    //grid-template-columns: 50% auto;
    //grid-template-rows: 40% auto;
    display: flex;
    flex-direction: row;
    .left { width: 50%; }
    .right { width: 50%;
      .item { border-left: 4px solid #dbedfe; }
      .item:first-child:after { content: ''; width: 100%; height: 4px; background: #4da7fa; opacity: 0.2;}}
    .item { display: flex; flex-direction: column; overflow: hidden;
      .title-bar { display: flex; padding: 4px 10px 4px 16px; align-items: center;
        .op > * { margin: 0 0 0 6px; }}
      &:first-child { grid-row-start: 1; grid-row-end: 3;
        &:after { width: 4px; }
        .item-inner { flex: 1; }}
      &:nth-child(2) { flex-direction: column;
        &:after { height: 4px; }}
      &:last-child { flex-direction: column;}
      .item-inner { display: flex; overflow: hidden; flex-direction: column; }}}
  .title-bar { background: #f6f6f6; border-bottom: 1px solid #85AFD6;
    h2 { margin-right: auto; font-size: 12px; font-weight: bold; }
    .op { display: flex; }}
  //.item:last-child .title-bar { border-top: 1px solid #4da7fa; }
}
</style>